package com.kaifamiao.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/download/image")
public class DownloadImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        final String filename = "开发喵.jpg";
        // 对文件名称进行编码
        final String name = URLEncoder.encode( filename, StandardCharsets.UTF_8 );
        // 指定需要下载的图片路径
        final String pathname = "D:/uploads/" + filename;
        // 创建读取指定图片的文件输入流
        InputStream in = new FileInputStream( pathname );

        // 设置响应头中`content-type`字段的值
        response.setHeader( "content-type", "image/jpeg" );
        // 当响应头中`content-disposition`字段取值为`attachment`时，浏览器会将图片保存至本地计算机
        response.setHeader( "content-disposition", "attachment;filename=" + name );

        // 获得用于向响应缓冲区输出数据的字节输出流
        OutputStream out = response.getOutputStream();
        // 将输入流读取到的数据写入到字节输出流
        in.transferTo( out ); // Java 9
        out.close();
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new ServletException( "获取个图片用什么POST请求？" );
    }

}
